package com.taotao.config;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author wangjin
 * @title: RateLimiter
 * @projectName sw-gateway
 * @description:
 * @date 2021/12/19 12:58
 */
public class RateLimiter {
    private volatile LinkedBlockingQueue linkedBlockingQueue = null;

    public RateLimiter(int permitsPerSecond) {
        //创建令牌桶存放数量
        linkedBlockingQueue = new LinkedBlockingQueue<String>(permitsPerSecond);
        //初始化令牌桶
        init(permitsPerSecond);
        //开启定时器 每隔1s 生成固定的token 到我们的令牌桶

    }

    public static RateLimiter create(int permitsPerSecond) {
        //创建令牌桶存放数量
        return new RateLimiter(permitsPerSecond);
    }

    public void init(int permitsPerSecond) {
        addToken(permitsPerSecond);
        //开启定时器，每隔1s生成固定的token加到我们的令牌桶
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {

                    try {
                        Thread.sleep(1000);
                        addToken(permitsPerSecond);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }

        }, "tokenThread").start();
    }

    public void addToken(int permitsPerSecond) {
        for (int i = 0; i < permitsPerSecond; i++) {
            //token生成规则
            linkedBlockingQueue.offer("#");
        }
    }

    /**
     * 返回true 获取token
     *
     * @return
     */

    public boolean tryAcquire() {
        return linkedBlockingQueue.poll() == null ? false : true;
    }

    public static void main(String[] args) {


        RateLimiter rateLimiter = RateLimiter.create(2);
        // boolean result=rateLimiter.tryAcquire();
        System.out.println(rateLimiter.tryAcquire());
        System.out.println(rateLimiter.tryAcquire());

    }
}
